package jaoso.framework.web.listener;

import jaoso.framework.exception.BusinessException;

import jaoso.framework.service.SecurityService;
import jaoso.framework.service.ServiceLocator;
import jaoso.framework.service.SetupService;

import jaoso.framework.util.JaosoConfig;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.context.ApplicationContext;

import org.springframework.web.context.support.WebApplicationContextUtils;

import java.io.File;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * @author Edgeloner edgeloner@yahoo.com.cn
 * @since 2004-12-16
 */
public class InitJaosoListener implements ServletContextListener
{
    private static Log log = LogFactory.getLog(InitJaosoListener.class);

    private ServletContext servletContext;

    /**
     * (non-Javadoc)
     * 
     * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent arg0)
    {
    }

    /**
     * (non-Javadoc)
     * 
     * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent event)
    {
        log.info("********* Initialized Jaoso now *********************");
        servletContext = event.getServletContext();
        //initContext();
        //initRootPath();
        //setupIfNecessary();
        initSecurity();
        log.info("********* Initialized Jaoso success *********************");
    }

    private void initContext()
    {
        ApplicationContext ctx = WebApplicationContextUtils
                .getRequiredWebApplicationContext(servletContext);
        ServiceLocator.getInstance().setContext(ctx);
    }

    private void initRootPath()
    {
        String rootPath = servletContext.getRealPath("/");
        rootPath = rootPath.endsWith(File.separator) ? rootPath
                : (rootPath + File.separator);
        ((JaosoConfig) ServiceLocator.getInstance().getService("jaosoConfig"))
                .setRootPath(rootPath);
    }

    private void initSecurity()
    {
        try
        {
            ApplicationContext ctx = WebApplicationContextUtils
            .getWebApplicationContext(servletContext);
            SecurityService securityService = (SecurityService) ctx.getBean("securityService");
            securityService.initSecurity();
        } catch (BusinessException e)
        {
            log.error("starting spring error: ", e);
            e.printStackTrace();
        }
    }

    private void setupIfNecessary()
    {
        ((SetupService) ServiceLocator.getInstance().getService("setupService"))
                .install();
    }
}